import cv2


def cvreverse():
    # 加载视频
    cap = cv2.VideoCapture('硅基授权-兰炎华.mp4')

    # 获取视频信息
    fps = cap.get(cv2.CAP_PROP_FPS)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # 创建输出视频
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))

    # 读取并存储所有帧到列表中
    frames = [frame for ret, frame in iter(lambda: cap.read(), (False, None)) if ret]

    # 倒序播放并写入输出视频
    for frame in reversed(frames):
        out.write(frame)

    # 释放资源
    cap.release()
    out.release()


from moviepy import VideoFileClip, AudioFileClip, AudioClip, concatenate_audioclips, concatenate_videoclips
import subprocess


def re2():
    input_path = "硅基授权-兰炎华.mp4"
    # 加载原始视频
    video = VideoFileClip("硅基授权-兰炎华.mp4")

    # 视频倒放（包括视频和音频）
    # reversed_video = video.with_fps(vfx.TimeMirror)
    # 创建倒放片段（使用 time_mirror）
    command = [
        'ffmpeg',  # Linux/macOS 示例路径
        '-i', input_path,
        '-vf', 'reverse',
        '-af', 'areverse',
        input_path + '_reversed.mp4'
    ]
    subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    reversed_clip = VideoFileClip(input_path + '_reversed.mp4')
    print(f"反转长度 {reversed_clip.duration} ")
    # 保存倒放后的视频（带声音）
    reversed_clip.write_videofile("output1.mp4", codec="libx264", audio_codec="aac")



def add2():
    audio_file = "/Users/lanyanhua/Documents/AI-test/F5-TTS-d81ac468-677d-4c01-ac57-c86b6b3b0d14.wav"  # 或 .wav 等格式

    audio_clip = AudioFileClip(audio_file)
    audio_duration = audio_clip.duration
    print(f"音频时长: {audio_duration:.2f} 秒")

    # 创建 2 秒的静音片段（左右声道都为 0）
    two_seconds_silence = AudioClip(lambda t: [0.0, 0.0], duration=2)

    # 将静音片段和原音频拼接起来： 静音 + 原音频 + 静音
    final_audio = concatenate_audioclips([two_seconds_silence, audio_clip, two_seconds_silence])
    print(f"最终音频时长: {final_audio.duration:.2f} 秒")
    final_audio.write_audiofile("output1.wav")



def loop_with_reverse(input_path, output_path, target_duration):
    # 加载原始视频
    clip = VideoFileClip(input_path)
    original_duration = clip.duration
    print(f"原视频时长: {original_duration:.2f} 秒")
    print(f"目标时长: {target_duration:.2f} 秒")

    if clip.duration > target_duration:
        # 裁剪到目标时长
        clip = clip.subclip(0, target_duration + 1)  # +1 秒以防止浮点误差
        print(f"最终视频时长: {clip.duration:.2f} 秒")
        # 写出结果
        clip.write_videofile(output_path, codec="libx264", audio_codec="aac", fps=clip.fps)
        print(f"✅ 剪切，保存至: {output_path}")
        return output_path

    # 运行命令 ffmpeg -i test/lan.mp4 -vf "reverse" -af "areverse" output_reversed.mp4

    # 创建倒放片段（使用 time_mirror）
    command = [
        'ffmpeg',  # Linux/macOS 示例路径
        '-i', input_path,
        '-vf', 'reverse',
        '-af', 'areverse',
        input_path + '_reversed.mp4'
    ]
    subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    reversed_clip = VideoFileClip(input_path + '_reversed.mp4')
    print(f"反转长度 {reversed_clip.duration} ")

    bounce_clip = concatenate_videoclips([clip, reversed_clip], method="compose")

    # 计算需要多少个来回才能接近目标时间
    bounce_duration = bounce_clip.duration
    print(f"拼接后的长度 {bounce_duration} 个来回")
    clips_needed = int(target_duration // bounce_duration) + 1

    # 拼接多个来回
    looped_clips = [bounce_clip] * clips_needed
    final_clip = concatenate_videoclips(looped_clips, method="compose")

    # 裁剪到目标时长
    final_clip = final_clip.subclip(0, target_duration + 1)  # +1 秒以防止浮点误差
    print(f"最终视频时长: {final_clip.duration:.2f} 秒")
    # 如果原视频有音频，可以保留或替换为静音/其他音频
    # final_clip = final_clip.without_audio()  # 可选：去除音频避免冲突

    # 写出结果
    final_clip.write_videofile(output_path, codec="libx264", audio_codec="aac", fps=clip.fps)
    print(f"✅ 已生成无卡顿循环视频，保存至: {output_path}")
    return output_path

def concat():
    audio_file = "/Users/lanyanhua/Downloads/036cc84c-0629-40ae-bc3a-1dd26dc2d3de.wav"

    audio_clip = AudioFileClip(audio_file)
    audio_duration = audio_clip.duration
    input_path = "/Users/lanyanhua/Downloads/俊杰_40975.mp4"

    input_path = loop_with_reverse(input_path, "俊杰_40975_output.mp4", audio_duration)

    video = VideoFileClip(input_path)
    # 将视频按10秒分割为多个片段，存入列表，便于分批处理
    clips_10s = [video.subclip(i, min(i + 10, video.duration)) for i in range(0, int(video.duration), 10)]
    print(f"共分割为 {len(clips_10s)} 个10秒片段")
    # 分割10秒list 分批处理





if __name__ == "__main__":
    concat()
    # cvreverse()
    # add2()
    print("倒放视频已生成")
